import { NIcon, useMessage } from "naive-ui";
import type { Component } from "vue";
import { h } from "vue";
import { ZoomIn24Filled, ZoomOut24Filled, ArrowReset24Filled } from '@vicons/fluent'
import { ref } from "vue";

interface zoomButton {
  text: string;
  icon: Component
}

const message = useMessage()
type ContainerEle = HTMLDivElement | null
let element: ContainerEle = null

export default function useZoomArea() {
  const setArea = (elementId: string) => {
    element = document.getElementById(elementId) as ContainerEle
    if (!element) {
      console.warn(`Element with id "${elementId}" not found`)
      return
    }
  }

  // 缩放参数
  let scale = ref(1);
  const scaleStep = 0.1;
  const maxScale = 3;
  const minScale = 1;
  // 拖拽参数
  const isDragging = ref(false);
  let startX: number, startY: number;
  let translateX = 0;
  let translateY = 0;
  let lastTranslateX = 0;
  let lastTranslateY = 0;

  const preventClick = ref(false)

  const updateZoom = () => {
    if (element) {
      element.style.transform = `scale(${scale.value}) translate(${translateX}px, ${translateY}px)`
    } else {
      message.warning('缩放有误，请刷新重试')
    }
  }

  const zoomIn = () => {
    if (scale.value < maxScale) {
      scale.value += scaleStep;
      updateZoom();
    }
  }
  const zoomOut = () => {
    if (scale.value > minScale) {
      scale.value -= scaleStep;
      updateZoom();
    }
  }
  const zoomReset = () => {
    scale.value = 1;
    translateX = 0;
    translateY = 0;
    lastTranslateX = 0;
    lastTranslateY = 0;
    updateZoom();
  }

  const icons: zoomButton[] = [
    { text: '放大', icon: h(NIcon, { size: 24, onClick: zoomIn }, () => h(ZoomIn24Filled)) },
    { text: '缩小', icon: h(NIcon, { size: 24, onClick: zoomOut }, () => h(ZoomOut24Filled)) },
    { text: '重置', icon: h(NIcon, { size: 24, onClick: zoomReset }, () => h(ArrowReset24Filled)) },
  ]

  const handleZoomMouseDownListen = (e: MouseEvent) => {
    if (scale.value === 1) return
    isDragging.value = true;
    startX = e.clientX - lastTranslateX;
    startY = e.clientY - lastTranslateY;
    preventClick.value = false
  }
  const handleZoomMouseMoveListen = (e: MouseEvent) => {
    if (!isDragging.value || scale.value === 1) return;

    translateX = e.clientX - startX;
    translateY = e.clientY - startY;
    updateZoom();
  }
  const handleZoomMouseUpListen = (e: MouseEvent) => {
    if (scale.value === 1) return
    isDragging.value = false;
    lastTranslateX = translateX;
    lastTranslateY = translateY;
    console.log('up zoom');
    preventClick.value = true
  }


  return { icons, setArea, isDragging, scale, handleZoomMouseDownListen, handleZoomMouseMoveListen, handleZoomMouseUpListen }
}
